package com.ufo.mybatistest2.controller;

import com.ufo.mybatistest2.Mapper.cardMapper;
import com.ufo.mybatistest2.Mapper.userMapper;
import com.ufo.mybatistest2.Service.*;
import com.ufo.mybatistest2.entity.Card;
import com.ufo.mybatistest2.entity.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Author ufo
 * @Description TODO
 * @Date 2021/1/15 11:37
 * @Version 1.0
 */


@RestController
@RequestMapping("/testBoot")
public class userController {


    @Autowired
    private userService userService;

    @Autowired
    private cardService cardService;

    private SqlSessionFactory factory;

    public userController(SqlSessionFactory factory) {
        this.factory = factory;
    }


    @RequestMapping("getUser/{id}")
    public String GetUser(@PathVariable int id) {
        return userService.Selabc(1).toString();
    }


    @RequestMapping("getUserLazy/{id}")
    public String Lazy(@PathVariable int id) {
        SqlSession session =factory.openSession();
        userMapper mapper = session.getMapper(userMapper.class);
        System.out.println("=========懒加载：第一次不加载全=========");
        User sel = mapper.Selabc(1);
        System.out.println("=========懒加载：用到才加载=========");
        System.out.println(sel.toString());
        System.out.println("=========一级缓存：再次查询直接用缓存=========");
        User sel2=mapper.Selabc(1);
        System.out.println(sel2.toString());
        session.commit();
        session.close();

        return "ok";
    }

    /**
     * 二级缓存测试
     * @return
     */
    @GetMapping("/getUser")
    public User getUser(){
        //二级缓存，不建议懒加载
        int time=4;
        for (int i = 0; i < time; i++) {
            System.out.println("=====第"+(i+1)+"次查询=====");
            System.out.println(userService.Selabc(1).toString());
        }
        return null;
    }


    @RequestMapping("getCardByuserid/{id}")
    public String card(@PathVariable int id) {
        List<Card> cards = cardService.SelectByUserId(1);
        System.out.println(cards.toString());
        return "ok";
    }
}

